﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    /// <summary>
    /// AudioSource对象缓存池，避免频繁创建AudioSource组件
    /// </summary>
    public sealed class AudioSourcePool
    {
        /// <summary>
        /// 播放节点
        /// </summary>
        private Transform audioPlayRoot;
        /// <summary>
        /// 缓存节点
        /// </summary>
        private Transform audioPoolRoot;
        private Stack<AudioSource> audioSourceStack = new Stack<AudioSource>();

        public AudioSourcePool(Transform playRoot,Transform poolRoot)
        {
            this.audioPlayRoot = playRoot;
            this.audioPoolRoot = poolRoot;
        }
        /// <summary>
        /// 从缓存池中获取一个空闲的AudioSource组件
        /// </summary>
        public AudioSource Pop(string soundname)
        {
            AudioSource audioSource;
            if(this.audioSourceStack.Count > 0)
            {
                audioSource = this.audioSourceStack.Pop();
                audioSource.name = soundname;
            }
            else
            {
                GameObject obj = new GameObject(soundname);
                audioSource = obj.AddComponent<AudioSource>();
            }

            audioSource.transform.parent = this.audioPlayRoot;
            audioSource.gameObject.SetActive(true);
            return audioSource;
        }
        /// <summary>
        /// 把一个AudioSource组件放回缓存池中
        /// </summary>
        public void Push(AudioSource sound)
        {
            sound.name = "Free Audio Source";
            sound.transform.parent = this.audioPoolRoot;
            sound.clip = null;
            sound.outputAudioMixerGroup = null;
            sound.gameObject.SetActive(false);
            audioSourceStack.Push(sound);

        }

    }
}

